/**
 * @Description 系统后台元数据表配置列表JS-systemDataConfigList.jsp
 * @Author guoyanfei
 * @Date 2018/12/25
 */

var postPath = '/gdp';
//项目路径
var strPath = window.document.location.pathname;
var configList = function () {
    //查询数据列表
    var getList = function () {
        $("#tb_configList").bootstrapTable({
            url: postPath + "/system/dataConfig/getCfgdbList",
            detailView: true,//父子表
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            cache: false, // 是否使用缓存
            singleSelect: true,
            columns: [{
                title: '数据库',
                field: 'dbMark',
                align: 'left',
                valign: 'middle'
            }, {
                title: '连接地址',
                field: 'dbIp',
                align: 'center',
                valign: 'middle',
                cellStyle: function (value, row, index) {
                    return {
                        css: {
                            "min-width": "80px",
                            "white-space": "nowrap",
                            "text-overflow": "ellipsis",
                            "overflow": "hidden",
                            "max-width": "220px"
                        }
                    }
                },
                formatter: function (value, row, index) {
                    return handColumnTip(value);
                }
            }, {
                title: '库名称',
                field: 'dbName',
                align: 'center',
                valign: 'middle'
            }, {
                title: '数据库类型',
                field: 'dbVersion',
                align: 'center',
                valign: 'middle',
            }, {
                title: '操作',
                field: 'option',
                align: 'center',
                valign: 'middle',
                formatter: function (value, row) {
                    var btn = "<button class='btn blue-steel' onclick='addtable(\"" + row.dbKey + "\");'><i class='fa fa-push'></i>新增表</button>";
                    btn += "<button class='btn blue-steel' onclick='loadtable(\"" + row.dbKey + "\",true);'><i class='fa fa-load'></i>同步所有表</button>";
                    return btn;
                }
            }],
            onExpandRow: function (index, row, $detail) {
                var tools = '<div class="table-toolbar" style="margin-bottom: 0px;">'
                    + '<div class="row" style="margin-left: 0px; margin-right: 0px;">'
                    + '<div class="col-md-3">'
                    + '<input id="seachTxt' + row.dbKey + '" type="text" class="form-control" placeholder="请输入关键字" />'
                    + '</div>'
                    + '<div class="col-md-3">'
                    + '<div class="btn-group">'
                    + "<button class='btn blue-steel' onclick='selectOption(\"tb_" + row.dbKey + "\");'>"
                    + '查询 <i class="fa fa-search"></i>'
                    + '</button></div></div>'
                    + '<div class="col-md-1">'
                    + '<div class="btn-group">'
                    + "<button class='btn blue-steel' onclick='selectFile()'> 批量导入 <i class='fa fa-compress'></i></button></div></div>"
                    + '<input type="file" id="file" onchange="getFilePath(\'' + row.dbKey + '\')" style="filter:alpha(opacity=0);opacity:0;width: 0;height: 0;"/>'
                    + '<div class="col-md-1">'
                    + '<div class="btn-group">'
                    + "<button class='btn blue-steel' onclick='exportTable(\"" + row.dbKey + "\");'>"
                    + '全表导出 <i class=\'fa fa-expand\'></i>'
                    + '</button></div></div>'
                    + '<div class="col-md-1">'
                    + '<div class="btn-group">'
                    + "<button class='btn blue-steel' onclick='truncateTable(\"" + row.dbKey + "\");'>"
                    + '一键清空 <i class=\'fa fa-times\'></i>'
                    + '</button></div></div>'
                    + '</div></div>';


                var cur_table = $detail.html(tools + '<table id="tb_' + row.dbKey + '"></table>').find('table');
                $(cur_table).bootstrapTable({
                    url: postPath + "/system/dataConfig/selectCfgtableList",
                    undefinedText: '-',
                    pagination: true, // 分页
                    striped: true, // 是否显示行间隔色
                    queryParams: function (pageReqeust) {
                        var temp = {
                            order: pageReqeust.order,
                            pageNo: pageReqeust.offset / pageReqeust.limit + 1,
                            pageSize: pageReqeust.limit,
                            dbkey: row.dbKey,
                            paramtxt: $("#seachTxt" + row.dbKey).val(),
                            tableType: 1
                        };
                        return temp;
                    },
                    cache: false, // 是否使用缓存
                    pageList: [5, 10, 20],
                    toolbar: "",// 指定工具栏
                    showColumns: false, // 显示隐藏列
                    showRefresh: false, // 显示刷新按钮
                    uniqueId: "dbKey", // 每一行的唯一标识
                    sidePagination: "server", // 服务端处理分页
                    columns: [{
                        title: '表标识',
                        field: 'dtConfigId',
                        align: 'center',
                        valign: 'middle',
                        sortable: false
                    }, {
                        title: '表中文名称',
                        field: 'dtNameCn', // 字段
                        align: 'center', // 对齐方式（左 中 右）
                        valign: 'middle', //
                        sortable: false
                    }, {
                        title: '表名称',
                        field: 'dtName',
                        align: 'center',
                        valign: 'middle',
                        sortable: false
                    }, {
                        title: '主键',
                        field: 'dtPrimarykey',
                        align: 'center',
                        valign: 'middle',
                        sortable: false
                    }, {
                        title: '操作',
                        field: 'option',
                        align: 'center',
                        valign: 'middle',
                        width: '200px',
                        sortable: false,
                        formatter: function (value, row, index) {
                            var btn = "<button class='btn blue-steel' onclick='updatetable(\"" + row.dtConfigId + "\");'><i class='fa fa-edit'></i>修改</button>"
                                + "<button class='btn blue-steel' onclick='deletetable(\"" + row.dtConfigId + "\",\"tb_" + row.dtConn + "\");'><i class='fa fa-remove'></i>删除</button>";
                            return btn;
                        }
                    }]

                });
            }
        });
    };


    return {
        init: function () {
            getList();
        }
    };
}();

//初始化
$(function () {
    configList.init();
});

/*
   * 处理列提示
   * */
function handColumnTip(value) {
    if (!value) return null;
    var span = document.createElement('span');
    span.setAttribute('title', value);
    span.innerHTML = value;
    return span.outerHTML;
}
//查询表操作
function selectOption(tableid) {
    $("#" + tableid).bootstrapTable('refresh');
};

//导出表操作
function exportTable(dbkey) {
    var url = postPath +  "/system/dataConfig/exportTable?dbkey=" + dbkey;
    document.location.href = url;
}

//导入表操作
function importTable(formData) {
    $.ajax({
        url: postPath + '/system/dataConfig/importTable',
        type: 'POST',
        dataType: "json",
        data: formData,
        // async : false,
        processData: false,
        contentType: false,
        // data: {filePath: $("#importpath").val(), dbkey: dbkey},
        beforeSend() {
            $.toast({
                text: '正在导入表数据，请稍后...',
                icon: 'info',
                allowToastClose: true,
                hideAfter: false,
                position: 'top-right',
                textAlign: 'left'
            });
        },
        success: function (data) {
            if (data['state'] > 0) {
                showMsg("导入成功! 耗时: " + data['time'] + " s", "success");
            } else if (data['state'] === -1) {
                showMsg("请导入Excel格式数据!", "warning")
            } else {
                showMsg("导入失败!", "error");
            }
        },
        error: function () {
            showMsg("导入失败,请刷新后重试!", "error");
        }
    });
};

//清空数据库列表
function truncateTable(dbkey) {

    var deleteFunction = function (result) {
        if(result == false)
            return;
        $.ajax({
            url: postPath + '/system/dataConfig/truncateTable',
            type: 'POST',
            dataType: "json",
            data: {dbkey: dbkey},

            beforeSend() {
                $.toast({
                    text: '正在清空列表，请稍后...',
                    icon: 'info',
                    allowToastClose: true,
                    hideAfter: false,
                    position: 'top-right',
                    textAlign: 'left'
                });
            },
            success: function (data) {
                if (data > 0) {
                    showMsg("清空成功!", "success");
                } else {
                    showMsg("清空失败!", "error");
                }
            },
            error: function () {
                showMsg("清空失败,请刷新后重试!", "error");
            }
        });
    }
    confirmDelete("删除所有表?", deleteFunction);
};


//新增表操作
function addtable(dbkey) {
    window.location.href = postPath + "/systemDataConfig/index?ismark=1&dbkey=" + dbkey;
}

//修改表操作
function updatetable(dtConfigId) {
    window.location.href = postPath + "/systemDataConfig/index?ismark=2&dtConfigId=" + dtConfigId;
}

//删除表操作
function deletetable(dtConfigId, tableid) {
    bootbox.confirm("确认删除(删除有关此表的所有信息)?", function (result) {
        if (result == false)
            return;
        $.ajax({
            url: postPath + '/system/dataConfig/delTableInfo',
            type: 'POST',
            data: {dtConfigId: dtConfigId},
            success: function (data) {
                if (data > 0) {
                    showMsg("删除成功!", "success");
                    selectOption(tableid);
                } else if (data == 0) {
                    bootbox.alert("请先删除服务相关配置!");
                } else {
                    showMsg("删除失败!", "error");
                }
            },
            error: function () {
                showMsg("删除失败,请刷新后重试!", "error");
            }
        });
    });
}

function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}

function selectFile() {
    //触发 文件选择的click事件
    $("#file").trigger("click");
}

function getFilePath(dbkey) {
    var formData = new FormData();
    formData.append("file", $("#file")[0].files[0]);
    formData.append("dbkey", dbkey);
    // systemIndex.prototype.importProjectData(formData);
    importTable(formData)
    $("#file").val("");
}

function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}

function loadtable(dbkey, ischeck) {

    var messageObj = {
        title : "确认同步所有数据库表?",
        message : dbkey,
        callback: function(result){
            if(result == false)
                return;

            $.ajax({
                url: postPath + '/system/dataConfig/loadTable',
                type: 'POST',
                dataType: "json",
                data: {dbkey: dbkey, ischeck: ischeck},
                beforeSend() {
                    $.toast({
                        text: '正在装载表数据，请稍后...',
                        icon: 'info',
                        allowToastClose: true,
                        hideAfter: false,
                        position: 'top-right',
                        textAlign: 'left'
                    });
                },
                success: function (data) {
                    if (data['state'] > 0) {
                        showMsg("装载成功! 耗时: " + data['time'] + " s", "success");
                    } else {
                        showMsg("装载失败!", "error");
                    }
                },
                error: function () {
                    // dialog.modal('hide');
                    showMsg("装载失败!请刷新后重试", "error")
                }
            });

        }
    }

    bootbox.confirm(messageObj)
}
